<template>
  <div class="wrapLimit clx main">
    <div>
      <div class="transportCapacityRecord">
        <!-- isCarrier {{isCarrier}} -->
        <el-form ref="inputModel" :rules="rules" :model="inputModel" class="form-baseinfo">
          <div class="insertInfo">
            <p class="title">退货基本信息</p>
            <div class="info">
              <el-form-item label="员工姓名" prop="">
                <el-input v-model="inputModel.userName" />
              </el-form-item>
              <el-form-item label="工号" prop="userJobNum">
                <el-input v-model="inputModel.userJobNum" />
              </el-form-item>
              <el-form-item label="卡号" prop="">
                <el-input v-model="inputModel.userCardNo" />
              </el-form-item>
              <el-form-item label="联系电话" prop="">
                <el-input v-model="inputModel.userMobile" />
              </el-form-item>
              <el-form-item label="所属部门" prop="">
                <el-input v-model="inputModel.departmentName" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="inputModel.remark" />
              </el-form-item>
            </div>
          </div>
        </el-form>

        <el-form
          ref="ordersProducts"
          :rules="rules"
          :inline="true"
          :model="inputModel.ordersProducts"
          class="form-baseinfo"
        >
          <div class="insertInfo">
            <p class="title">退货物料信息</p>
            <!-- <el-form-item label="产品类型" prop="categoryNo">
                        <el-select filterable clearable style="width: 150px;" v-model="inputModel.ordersProducts.categoryNo"
                            @change="centreTypeChange">
                            <el-option v-for="item in centreType" :key="item.id" :value="item.categoryNo"
                                :label="item.cName">
                            </el-option>
                        </el-select>
                    </el-form-item> -->
            <div class="info">
              <el-form-item label="物料名称" prop="pNo" style="margin-right: 0">
                <el-select v-model="inputModel.ordersProducts.pNo" filterable clearable>
                  <el-option v-for="item in smallType" :key="item.id" :value="item.pNo" :label="item.pTitle" />
                </el-select>
              </el-form-item>
              <el-form-item label="退货数量" prop="pCount">
                <el-input-number v-model="inputModel.ordersProducts.pCount" :precision="0" :controls="false" :min="1" />
                <el-button class="addBtn" size="medium" type="text" @click="insertData('ordersProducts')">
                  + 添加
                </el-button>
              </el-form-item>
            </div>
          </div>
          <LPTablePage
            :show-index="true"
            :show-indexfixed="false"
            index-label="序号"
            :table-data="tableData"
            :table-column="tableColumn"
            :current-page="currentPage"
            :show-page="false"
            align="center"
          >
            <template slot="couponModels" slot-scope="{ row }">
              <div v-if="row.couponModels.length > 0">
                <div v-for="(item, index) in row.couponModels" :key="index">
                  <el-link type="primary" @click="goToCouponManage(item.couponId)">{{ item.couponName }}</el-link>
                </div>
              </div>
            </template>
            <template slot="couponRecordId" slot-scope="{ row }">
              <div v-if="row.couponModels.length > 0">
                <div v-for="(item, index) in row.couponModels" :key="index">
                  <div>{{ item.recordId }}</div>
                </div>
              </div>
            </template>
            <template slot="cz" slot-scope="scope">
              <el-button type="text" @click="deleteInfo(scope.$index)">删除</el-button>
            </template>
          </LPTablePage>
          <span class="collect"
            >汇总：一共{{ totalProduct }}件商品，总金额{{ Math.round(totalAmount * 100) / 100 }}元</span
          >
          <div style="margin-top: 20px">
            <el-button class="button" @click="close()">关闭</el-button>
            <el-button class="button" type="primary" @click="Save('inputModel')">提交审核</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getReturnProductList } from '@/api/LaborProtection/order'
import { getCategoryInfo } from '@/api/LaborProtection/categoryInfo'
import { getProductList } from '@/api/LaborProtection/product'
import { closeActiveTag } from '@/utils/lpUtils.js'
import { insertReturnOrder } from '@/api/LaborProtection/returnOrder'
import LPTablePage from '@/components/LPTablePage/index.vue'

export default {
  name: 'ReturnOrderManageInsertReOrder',
  components: { LPTablePage },
  data() {
    return {
      data: {},
      inputModel: {
        orType: 0,
        userName: '',
        userCardNo: '',
        userJobNum: '',
        userMobile: '',
        plantName: '',
        departmentName: '',
        jobName: '',
        remark: '',
        finishRemark: '',
        ordersProducts: {
          categoryNo: '',
          pNo: '',
          pCount: undefined
        }
      },
      rules: {
        userName: [{ required: true, message: '请输入下单人姓名', trigger: 'blur' }],
        userMobile: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        userJobNum: [{ required: true, message: '请输入工号', trigger: 'blur' }],
        userCardNo: [{ required: true, message: '请输入卡号', trigger: 'blur' }],
        departmentName: [{ required: true, message: '请输入所属部门', trigger: 'blur' }],
        pNo: [{ required: true, message: '请选择物料名称', trigger: 'blur' }],
        pCount: [{ required: true, message: '请输入退货数量', trigger: 'blur' }],
        categoryNo: [{ required: true, message: '请选择物料类型', trigger: 'blur' }]
      },
      centreType: [],
      smallType: [],
      tableData: [],
      tableColumn: [
        { label: '物料类型', prop: 'pClassName' },
        { label: '物料编码', prop: 'pNo' },
        { label: '物料名称', prop: 'pTitle' },
        { label: '单位', prop: 'pUnit' },
        { label: '数量', prop: 'newRPCount' },
        { label: '优惠券名称', prop: 'couponModels', width: 140, render: true },
        { label: '优惠券发放编号', prop: 'couponRecordId', width: 140, render: true },
        { label: '物料销售单价', prop: 'pPrice' },
        { label: '退款金额', prop: 'pMoney' },
        { label: '操作', prop: 'cz', render: true }
      ],
      totalAmount: 0,
      totalProduct: 0,
      total: 0,
      currentPage: 1,
      pageSize: 10
    }
  },
  mounted() {
    this.getCategoryInfo(2)
    this.getProductList()
  },
  methods: {
    goToCouponManage(id) {
      this.$router.push({
        path: '/laborProtection/couponManage',
        query: {
          data: JSON.stringify({
            id: id,
            back: '/laborProtection/order'
          })
        }
      })
    },
    /**
     *  1：大类 2：中类 3：小类
     * @param {*} type
     */
    getCategoryInfo(type) {
      const data = {
        CCLass: type,
        SkipCount: 0
      }
      getCategoryInfo(data).then((res) => {
        if (!res.error) {
          this.centreType = res.items
        }
      })
    },
    getProductList(QCategoryNo) {
      const params = {
        PType: 0,
        // QCategoryNo: QCategoryNo,
        SkipCount: 0
      }
      getProductList(params).then((res) => {
        this.smallType = res.items
      })
    },
    centreTypeChange() {
      this.inputModel.ordersProducts.pNo = ''
      if (this.inputModel.ordersProducts.categoryNo == '') {
        this.smallType = []
      } else {
        this.getProductList(this.inputModel.ordersProducts.categoryNo)
      }
    },
    deleteInfo(index) {
      this.$confirm('是否删除该条产品信息', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      })
        .then(({ value }) => {
          this.$message.success('删除成功')
          this.tableData.splice(index, 1)
          this.totalAmount = 0
          this.totalProduct = 0
          this.tableData.forEach((item) => {
            this.totalAmount = Math.round((this.totalAmount + item.pMoney) * 100) / 100
            this.totalProduct = this.totalProduct + item.newRPCount
          })
        })
        .catch(() => {})
    },
    insertData(ordersProducts) {
      this.$refs[ordersProducts].validate((valid) => {
        if (valid) {
          if (this.inputModel.userJobNum.length == 0) {
            return this.$message.error('请先输入工号')
          }
          if (this.tableData.length > 0) {
            let falg = false
            const falg1 = this.tableData.every((item) => item.userJobNum == this.inputModel.userJobNum)
            this.tableData.forEach((item) => {
              if (item.pNo == this.inputModel.ordersProducts.pNo) {
                falg = true
              }
            })
            if (!falg1) {
              return this.$message.error('不可用他人卡号进行退货操作')
            }
            if (falg) {
              return this.$message.error('不可申请俩次同一种物料')
            }
          }
          const params = {
            PNo: this.inputModel.ordersProducts.pNo,
            UserJobNum: this.inputModel.userJobNum,
            ReutrnCount: this.inputModel.ordersProducts.pCount
          }
          getReturnProductList(params)
            .then((res) => {
              res.items.forEach((item) => {
                this.tableData.push(item)
                this.totalAmount = Math.round((this.totalAmount + item.pMoney) * 100) / 100
                this.totalProduct = this.totalProduct + item.newRPCount
              })
              this.initialData()
            })
            .catch((err) => {
              if (err.response.data.error.code == 'LaborProtection:30006') {
                this.$message.error('当月未购买过该商品，无法退货。')
                this.initialData()
              } else if (err.response.data.error.code == 'LaborProtection:30009') {
                this.$message.error(err.response.data.error.message)
                this.inputModel.ordersProducts.pCount = undefined
              } else {
                this.$message.error(err.response.data.error.message)
              }
            })
        } else {
          return false
        }
      })
    },
    initialData() {
      this.inputModel.ordersProducts = {
        pNo: '',
        categoryNo: '',
        pCount: undefined
      }
    },
    /**
     * 数组去重
     * @param {*} arr
     * @returns
     */
    unique(arr) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr.pNo) && res.set(arr.pNo, arr.pNo))
    },

    Save(inputModel) {
      this.$refs[inputModel].validate((valid) => {
        if (valid) {
          if (this.tableData.length == 0) {
            return this.$message.error('退货产品信息至少为一条')
          }
          let tempList = []
          const ordersReturnProducts = []
          tempList = JSON.parse(JSON.stringify(this.unique(this.tableData)))
          tempList.forEach((item) => {
            item.newRPCount = 0
            this.tableData.forEach((item1) => {
              if (item.pNo == item1.pNo) {
                item.newRPCount = item.newRPCount + item1.newRPCount
              }
            })
          })
          console.log(tempList)
          tempList.forEach((item) => {
            ordersReturnProducts.push({
              pNo: item.pNo,
              orpCount: item.newRPCount
            })
          })
          const data = {
            orType: 1,
            userName: this.inputModel.userName,
            userCardNo: this.inputModel.userCardNo,
            userJobNum: this.inputModel.userJobNum,
            userMobile: this.inputModel.userMobile,
            departmentName: this.inputModel.departmentName,
            remark: this.inputModel.remark,
            ordersReturnProducts: ordersReturnProducts
          }
          insertReturnOrder(data).then((res) => {
            if (!res.error) {
              this.$message.success('已提交审核')
              this.close()
            }
          })
        } else {
          return false
        }
      })
    },
    close() {
      closeActiveTag(this, '/laborProtection/order/returnOrderManage')
    }
  }
}
</script>

<style lang="scss" scoped>
.transportCapacityRecord {
  margin: 0 45px;
  .form-baseinfo {
    .title {
      font-size: 16px;
      font-weight: 600;
    }
  }

  ::v-deep .BeginTime {
    width: 1.8rem;
  }
}

::v-deep .el-form-item__label {
  text-align: left;
  font-weight: normal;
  color: #333333;
  line-height: 30px;
}
.insertInfo {
  .info {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: end;
    // margin: 0 45px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ededed;

    .el-form-item {
      display: flex;
      flex-direction: column;
      width: calc(32%);
      height: auto;
      // margin-bottom: 80px;
      &:nth-child(2) {
        position: relative;
      }
    }
    ::v-deep .el-input__inner {
      width: 400px;
      height: 36px;
      background: #ffffff;
      border-radius: 4px;
      border: 1px solid #d8d8d8;
    }
    .addBtn {
      position: absolute;
      right: 27%;
    }
  }
}
.collect {
  display: block;
  padding-left: 20px;
  width: 100%;
  height: 40px;
  line-height: 40px;
  background-color: #f2f3f5;
}
.title {
  margin-left: 10px;
  padding: 20px 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  &::before {
    content: '';
    display: inline-block;
    width: 3px;
    height: 16px;
    position: absolute;
    left: 45px;
    background: #0076ff;
  }
}

.button {
  width: 100px;
  position: relative;
  left: 45%;
  top: 30px;
  margin: 0 40px;
  transform: translate(-50%);

  &:nth-of-type(1) {
    color: #333333;
    background-color: #fff;
  }
}
</style>
